import {
  createRouter as createVueRouter,
  createMemoryHistory,
  createWebHistory,
  type RouteLocation,
} from 'vue-router';
import type { I18n } from '../i18n';
import { setTitleForClient } from '../utils/other';
import type { Pinia } from 'pinia';
import { useAppStore } from '@/home/stores/app';
import { $fetch } from '../utils/fetch';
import { HEADER_KEY_COMMUNITY, HEADER_KEY_LANGUAGE, HEADER_KEY_TOKEN } from '@/common/utils/constants';
import { getDeviceId } from '@/common/utils/stats';

export function createRouter({ i18n, pinia, language, communityName, token }: { i18n: I18n, pinia: Pinia, language: string, communityName: string, token: string }) {
  // const isZh = i18n.global.locale.value === 'zh-CN';

  // 定义路由，注意：不建议使用 name 属性，只有在必要的时候才使用 name 属性
  // 因为多语言的关系，一定要在 createRouter 内部定义路由

  // meta.autoSetTitle 传递 false 表示标题由组件直接控制，导航守卫不进行干预，如果组件不控制，则标题不变

  const routes = [
    {
      path: '/',
      component: () => import('../views/home/index.vue'),
      meta: {
      },
    },

    {
      path: '/explore',
      redirect: '/explore/journalism',
      component: () => import('../views/explore/index.vue'),
      meta: {
      },
      children: [
        {
          path: 'journalism/:type?/:page?',
          component: () => import('../views/explore/sub/journalism.vue'),
          props: true,
          meta: {
            autoSetTitle: false,
          },
        },
        {
          path: 'organization/:type?/:page?',
          component: () => import('../views/explore/sub/organization.vue'),
          props: true,
          meta: {
            autoSetTitle: false,
          },
        },
        {
          path: 'developer/:page?',
          component: () => import('../views/explore/sub/developer.vue'),
          props: true,
          meta: {
            title: i18n.global.t('home.explore.developer.title'),
          },
        },
        {
          path: 'repository/:type?/:page?',
          component: () => import('../views/explore/sub/repository.vue'),
          props: true,
          meta: {
            autoSetTitle: false,
          },
        },
      ],
    },
    {
      path: '/explore/journalism/detail/:id',
      component: () => import('../views/explore/detail.vue'),
      props: (route: RouteLocation) => ({ id: route.params.id, pageType: 'detail' }),
      meta: {
        autoSetTitle: false,
      },
    },
    {
      path: '/explore/journalism/preview/:id',
      component: () => import('../views/explore/detail.vue'),
      props: (route: RouteLocation) => ({ id: route.params.id, pageType: 'preview' }),
      meta: {
        autoSetTitle: false,
      },
    },

    {
      path: '/subscription/unsubscribe',
      component: () => import('../views/subscription/unsubscribe.vue'),
      props: (route: RouteLocation) => ({
        name: route.query.name,
        email: route.query.email,
      }),
      meta: {
        title: i18n.global.t('home.subscription.unsubscribe.title'),
      },
    },

    {
      path: '/search',
      component: () => import('../views/digest/search.vue'),
      props: (route: RouteLocation) => ({ type: route.query.type, query: route.query.q }),
      meta: {
        title: i18n.global.t('home.search.index.title'),
      },
    },

    {
      path: '/tag/:id/:type?',
      component: () => import('../views/digest/tag.vue'),
      props: true,
      meta: {
        autoSetTitle: false,
      },
    },

    {
      path: '/column/detail/:id',
      component: () => import('../views/digest/column.vue'),
      props: true,
      meta: {
        autoSetTitle: false,
      },
    },

    // 注意：404 路由，业务路由都要放在这前面
    {
      path: '/:pathMatch(.*)*',
      alias: '/404',
      component: () => import('../views/common/404.vue'),
      meta: {
        title: '404 Not Found',
      },
    },
  ];

  const router = createVueRouter({
    history: import.meta.env.SSR ? createMemoryHistory(import.meta.env.MICRO_SITE_BASE_URL) : createWebHistory(import.meta.env.MICRO_SITE_BASE_URL),
    routes,
    scrollBehavior() {
      return { top: 0 };
    },
  });

  router.beforeEach((to) => {
    if (!import.meta.env.SSR) {
      if (to.meta.autoSetTitle !== false) {
        const store = useAppStore(pinia);

        setTitleForClient(to.meta.title as string, store.config.seo.title || store.config.name);
      }
    }
  });

  router.afterEach((to) => {
    if (!import.meta.env.SSR) {
      // 统计埋点
      const headers: Record<string, any> = {
        [HEADER_KEY_COMMUNITY]: communityName,
        [HEADER_KEY_LANGUAGE]: language,
      }
      token && (headers[HEADER_KEY_TOKEN] = token);
      $fetch('/record/doRecord', {
        method: 'post',
        headers,
        data: {
          deviceId: getDeviceId(),
        },
      });

      if (window._oafs) {
        if (to.meta.lazyStats !== true) {
          setTimeout(() => {
            window._oafs.setDefault('pageId', document.title);
            window._oafs.pv();
          });
        }
      }

      if (window._hmt) {
        setTimeout(() => {
          window._hmt.push(['_trackPageview', to.path]);
        });
      }
    }
  });

  return router;
}
